package com.ruyuan.seckilling.inventory.controller;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.inventory.service.InventoryService;
import com.ruyuan.seckilling.inventory.vo.CleanStockRequest;
import com.ruyuan.seckilling.inventory.vo.ProductStockVo;
import com.ruyuan.seckilling.inventory.vo.QueryCurrentStockRequest;
import com.ruyuan.seckilling.inventory.vo.SyncProductStockRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhonghuashishan
 */
@Slf4j
@RestController
@RequestMapping("/inventory")
public class InventoryController {

    @Autowired
    private InventoryService inventoryService;

    @PostMapping("/syncStock")
    Boolean syncStock(@RequestBody List<SyncProductStockRequest> request) {
        for (SyncProductStockRequest syncProductStockRequest : request) {
            inventoryService.syncStock(syncProductStockRequest.getActivityId(),
                    syncProductStockRequest.getSkuId(), syncProductStockRequest.getSeckillingStock());
            log.info("同步商品库存, syncProductStockRequest={}", JSON.toJSONString(syncProductStockRequest));
        }
        return Boolean.TRUE;
    }

    @PostMapping("/queryCurrentStock")
    List<ProductStockVo> queryCurrentStock(@RequestBody QueryCurrentStockRequest request) {
        List<ProductStockVo> resultList = new ArrayList<>();
        Long activityId = request.getActivityId();
        for (Long skuId: request.getSkuIds()) {
            ProductStockVo productStockVo = inventoryService.queryCurrentStock(activityId, skuId);
            resultList.add(productStockVo);
        }
        return resultList;
    }

    @PostMapping("/cleanStock")
    List<ProductStockVo> cleanStock(@RequestBody CleanStockRequest request) {
        List<ProductStockVo> resultList = new ArrayList<>();
        Long activityId = request.getActivityId();
        // 查询库存&删除库存
        for (Long skuId: request.getSkuIds()) {
            ProductStockVo productStockVo = inventoryService.queryCurrentStock(activityId, skuId);
            inventoryService.cleanStock(activityId, skuId);
            resultList.add(productStockVo);
        }
        return resultList;
    }
}
